package cn.deschen.common.utils;

import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author hanbin_chen
 * @Description Http工具
 * @DateTime 2021/6/1
 * @Version V1.0.0
 */
public final class HttpUtil {

    /**
     * 用于覆盖默认的公共空构造
     */
    private HttpUtil() {
    }


    /**
     * 获取请求
     * @return
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null == attributes) {
            return null;
        }
        return attributes.getRequest();
    }

    /**
     * 获取响应
     * @return
     */
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null == attributes) {
            return null;
        }
        return attributes.getResponse();
    }

    /**
     * 获取请求头
     * @param name 请求头名称
     * @return
     */
    public static String getHeader(String name) {
        HttpServletRequest request = getRequest();
        if (null == request) {
            return null;
        }
        return request.getHeader(name);
    }

    /**
     * 获取流水号
     */
    public static String getTransId() {
        HttpServletRequest request = getRequest();
        if (null == request) {
            return NoUtil.getNo();
        }
        Object value = request.getAttribute("transId");
        if (value instanceof String && !StringUtils.isEmpty(value)) {
            return value.toString();
        }
        return NoUtil.getNo();
    }

}
